package com.example.idlefish.Goods

import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.GoodsInfo.ActivityContract.CreateGoodActivityContract
import com.example.idlefish.GoodsInfo.ActivityContract.GooddResultContract
import com.example.idlefish.GoodsInfo.ActivityContract.KindGoodClassifyContract
import com.example.idlefish.GoodsInfo.GoodContentActivity
import com.example.idlefish.GoodsInfo.KindGoodListActivity
import com.example.idlefish.GoodsInfo.parseGson.parseEaseGoodInfo
import com.example.idlefish.GoodsInfo.pojo.EaseGoodInfo
import com.example.idlefish.GoodsInfo.pojo.Pair
import com.example.idlefish.HomeAndSearch.SearchActivity
import com.example.idlefish.MyAccount.contract.HomepageContract
import com.example.idlefish.MyAccount.contract.LoginContract
import com.example.idlefish.PublicModule.ApplicationConst
import com.example.idlefish.PublicModule.ApplicationConst.server_ip
import com.example.idlefish.PublicModule.UserConst
import com.example.idlefish.R
import com.example.idlefish.databinding.GoodsMainBinding
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class GoodsMainFragment :  BottomSheetDialogFragment(){
    private lateinit var binding: GoodsMainBinding
    private val loginLauncher = registerForActivityResult(LoginContract()){
        result->
        if(UserConst.id > 0) {
            createGoodActivityLauncher.launch(Unit)
            Toast.makeText(context, "登录成功", Toast.LENGTH_LONG).show()
        }
        else{
            Toast.makeText(context, "登录失败请重试", Toast.LENGTH_LONG).show()
        }
    }
    private val homepageLauncher = registerForActivityResult(HomepageContract()) { result ->

    }
    private val lstPic = ArrayList<Bitmap>()
    private val lstAvatar = ArrayList<Bitmap>()
    private val lstGood = ArrayList<EaseGoodInfo>()

    private val classifyLauncher = registerForActivityResult(KindGoodClassifyContract()){
        result->
    }
    private val createGoodActivityLauncher = registerForActivityResult(CreateGoodActivityContract()){
        result->
        Log.d("returns", result.toString())
        if (result != null) {
            if(result > 0)
                goodContentLauncher.launch(result)
            else
            {
                Log.d("goodIndex", "返回index不成功")
            }
        }
        Log.d("goodIndex", "返回index为null")
    }
    private val goodContentLauncher = registerForActivityResult(GooddResultContract()){
            result->

    }
    private lateinit var  goodCardAdapter:GoodCardAdapter


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = GoodsMainBinding.inflate(layoutInflater)

        binding.showGoodRV.layoutManager = GridLayoutManager(requireContext(), 2)
        goodCardAdapter = GoodCardAdapter(lstGood)
        binding.showGoodRV.adapter = goodCardAdapter
        Init()
        binding.createGoodIV.setOnClickListener {
            if(UserConst.id < 0)
            {
                loginLauncher.launch(123)
            }
            else{
                createGoodActivityLauncher.launch(Unit)
            }
        }
        binding.goodSV.setOnClickListener{
            val intent = Intent(context, SearchActivity::class.java)
            startActivity(intent)
        }
        binding.secondHandCar.setOnClickListener {
            val tep = Pair("二手车", "车")
            classifyLauncher.launch(tep)
        }
        binding.goodrentlocal.setOnClickListener {
            val tep = Pair("租房", "房")
            classifyLauncher.launch(tep)
        }
        binding.goodhouse.setOnClickListener {
            val tep = Pair("二手房", "二手房")
            classifyLauncher.launch(tep)
        }
        binding.goodrent.setOnClickListener {
            val tep = Pair("本地租", "房")
            classifyLauncher.launch(tep)
        }
        binding.cat.setOnClickListener {
            val tep = Pair("萌宠", "萌宠")
            classifyLauncher.launch(tep)
        }
        binding.tag1.setOnClickListener {
            val tep = Pair("捡漏", "券")
            classifyLauncher.launch(tep)
        }
        binding.tag2.setOnClickListener {
            val tep = Pair("餐饮美食", "餐")
            classifyLauncher.launch(tep)
        }
        binding.tag2.setOnClickListener {
            val tep = Pair("餐饮美食", "餐")
            classifyLauncher.launch(tep)
        }
        binding.tag3.setOnClickListener {
            val tep = Pair("票务演出", "票")
            classifyLauncher.launch(tep)
        }
        binding.tag4.setOnClickListener {
            val tep = Pair("快递代发", "代")
            classifyLauncher.launch(tep)
        }
        binding.tag5.setOnClickListener {
            val tep = Pair("省钱出游", "票")
            classifyLauncher.launch(tep)
        }
        binding.tag6.setOnClickListener {
            val tep = Pair("同城跑腿", "代")
            classifyLauncher.launch(tep)
        }
        binding.tag7.setOnClickListener {
            val tep = Pair("陪练陪玩", "练")
            classifyLauncher.launch(tep)
        }
        binding.tag8.setOnClickListener {
            val tep = Pair("1v1私教", "练")
            classifyLauncher.launch(tep)
        }
        binding.tag9.setOnClickListener {
            val tep = Pair("本地约拍", "摄影")
            classifyLauncher.launch(tep)
        }
        binding.tag10.setOnClickListener {
            val tep = Pair("家庭维修", "维修")
            classifyLauncher.launch(tep)
        }
        binding.tag11.setOnClickListener {
            val tep = Pair("上门服务", "维修")
            classifyLauncher.launch(tep)
        }
        binding.tag12.setOnClickListener {
            val tep = Pair("上门回收", "代")
            classifyLauncher.launch(tep)
        }

        return binding.root
    }
    private class GoodCardViewHolder(view:View):RecyclerView.ViewHolder(view){
        val rGoodImage = view.findViewById<ImageView>(R.id.rGoodImage)
        val rName = view.findViewById<TextView>(R.id.rName)
        val rPrice = view.findViewById<TextView>(R.id.rPrice)
        val rWanting = view.findViewById<TextView>(R.id.rWanting)
        val rSellerAvatar = view.findViewById<ImageView>(R.id.rSellerAvatar)
        val rAdvantage = view.findViewById<TextView>(R.id.rAdvantage)
        val userClickArea = view.findViewById<LinearLayout>(R.id.userClickArea)
    }
    inner private class GoodCardAdapter(val lstGood:ArrayList<EaseGoodInfo>):RecyclerView.Adapter<GoodCardViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GoodCardViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.recommand_good_layout, parent, false)
            val viewHolder = GoodCardViewHolder(view)
            viewHolder.userClickArea.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                val userId = lstGood[index].userId
                homepageLauncher.launch(userId)
            }
            viewHolder.rGoodImage.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                val goodId = lstGood[index].goodId
                goodContentLauncher.launch(goodId)
            }
            viewHolder.rPrice.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                val goodId = lstGood[index].goodId
                goodContentLauncher.launch(goodId)
            }
            viewHolder.rWanting.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                val goodId = lstGood[index].goodId
                goodContentLauncher.launch(goodId)
            }
            return viewHolder
        }

        override fun onBindViewHolder(holder: GoodCardViewHolder, position: Int) {
            val info = lstGood[position]
            holder.rGoodImage.setImageBitmap(lstPic[position])
            holder.rName.text = info.goodName
            holder.rPrice.text = info.price.toString()
            holder.rWanting.text = info.want.toString() + "人想要"
            holder.rAdvantage.text = info.advantage
            holder.rSellerAvatar.setImageBitmap(lstAvatar[position])
        }

        override fun getItemCount(): Int {
            return lstGood.size
        }
    }
    fun Init()
    {
        netForGoods(object : Callback{
            override fun onFailure(call: Call, e: IOException) {
                Log.d("hello", "网络请求商品kindList失败")
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d("hello", "网络请求商品kindList成功")
                val responseData = response.body?.string().toString()
                val result = parseEaseGoodInfo.parseEaseGoodInfo(responseData)
                Log.i("商品主页的列表{}", result.toString())
                lstGood.addAll(result)
                requireActivity().runOnUiThread {
                    for ((index, tep) in result.withIndex()) {
                        val bitmap = ApplicationConst.decodeBase64ToImage(requireContext(), tep.goodPic1)
                        if (bitmap!= null)
                            lstPic.add(bitmap)
                        else{
                            lstPic.add(BitmapFactory.decodeResource(resources, R.drawable.null_product))
                        }
                        val avatar = ApplicationConst.decodeBase64ToImage(requireContext(), tep.userAvatar)
                        if (avatar!= null)
                            lstAvatar.add(avatar)
                        else{
                            lstAvatar.add(BitmapFactory.decodeResource(resources, R.drawable.default_image))
                        }
                    }
                    goodCardAdapter.notifyDataSetChanged()
                }
            }
        })
    }
    fun netForGoods(callback: Callback)
    {
        val client = OkHttpClient()
        val jsp = "http://$server_ip:8080/listGoodRandom"
        val request = Request.Builder()
            .header("Accept", "application/json") // 添加 Accept 头
            .url(jsp).get().build()
        client.newCall(request).enqueue(callback)
    }
}

